package com.bi.cloud.jwt;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * jwt 增强jwt，添加自定义信息
 */

@Component
public class JwtTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Map<String, Object> map = new HashMap<>();
        // 1. 获取认证信息
        // 客户端
        String clientId = authentication.getOAuth2Request().getClientId();// 客户端ID
        //Set<String> resourceIds = authentication.getOAuth2Request().getResourceIds(); // 资源集合
        // 用户
        Authentication userAuthentication = authentication.getUserAuthentication();
        Object principal = userAuthentication.getPrincipal();
        if (principal instanceof User){
            User user= (User) principal;
            map.put("userName", user.getUsername());
        }
        // 2.设置到accessToken中
        //map.put("resourceIds", resourceIds);
        map.put("clientId", clientId);
        map.put("three", "可添加任何信息");
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
        return accessToken;
    }
}

